package com.kx.core.validate.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kx.core.jdbc.domain.City;
import com.kx.core.jdbc.service.CityService;

/**
 * 表单验证
 * @author     Kangx.li 1703054
 * @version    V1 2018年11月26日
 * @since      Java
 */
@Controller
@RequestMapping(value="/citys")
public class CityValidateController {
    
    @Autowired
    private CityService cityService;
    
    @RequestMapping(method=RequestMethod.GET)
    public String getCityList(ModelMap map) {
	map.addAttribute("cityList",cityService.findAllCity());
	return "cityList";
    }
    
    @RequestMapping(value="/create",method = RequestMethod.GET)
    public String createCityForm(ModelMap map) {
	map.addAttribute("city",new City());
	map.addAttribute("action","create");
	return "cityForm";
    }
    
    @RequestMapping(value="/create",method=RequestMethod.POST)
    public String postCity(ModelMap map,
	    @ModelAttribute @Valid City city,
	    BindingResult bindingResult) {
	if(bindingResult.hasErrors()) {
	    map.addAttribute("action","create");
//	    int errorCount = bindingResult.getErrorCount();
//	    List<ObjectError> errorList = bindingResult.getAllErrors();
//	    map.addAttribute("error",errorList);
	    return "cityForm";
	}
	cityService.saveCity(city);
	return "redirect:/citys/";
    }
}

